import { useEffect, useMemo, useRef, useState } from "react";
import styles from "./index.module.less";
import SearchBox from "@/components/SearchBox";
import { TABLE_COLUMNS, TABS, TAB_VALUES, getSearchOptions } from "./constant";
import { Flex, Space, Tabs } from "antd";
import SuperTable from "@/components/SuperTable";
import { useNavigate } from "react-router-dom";
import { getTableData } from "@/api/modules/transactionManagement";
import JudgeStatus from "./JudgeStatus";
import useRefundOperation from "./useRefundOperation";
import cs from "classnames";
import { map } from "lodash";
import useUrl from "@/hooks/useUrl";

interface Props {
	isDashboard?: boolean;
}

export default (props: Props) => {
	const { isDashboard } = props;
	const { navigate, query } = useUrl();
	const [params, setParams] = useState({});
	const [tabValueInfo, setTabValueInfo] = useState<any>({
		status: isDashboard ? TAB_VALUES.all : query.get("status") ?? TAB_VALUES.all
	});
	const [expandedRowKeys, setExpandedRowKeys] = useState([]);
	const { isWaitSales, isSales, isInRefunded, isSalesSuccess, isInRefundedWaitAudit, isContinueSend, isPartialDelivery } =
		JudgeStatus;
	const { onAgree, onRefuse } = useRefundOperation({
		successCallback: () =>
			setParams(e => ({
				...e,
				timeStamp: Date.now()
			}))
	});

	const handleSearch = e => {
		setParams(e);
	};

	const handleRequest = async (params: any) => {
		const res = await getTableData({
			limit: params.pageSize,
			page: params.current,
			order_id: params.order_id ?? "",
			order_status: params.order_status ?? "",
			product_name: params.product_name ?? "",
			shop_name: params.shop_name ?? "",
			status: params.status ?? TAB_VALUES.all
		});
		setExpandedRowKeys(map(res?.data, "order_id"));
		return {
			total: res?.total ?? 0,
			data: res?.data ?? []
		};
	};

	const items = TABS;

	const detail = {
			label: "详情",
			value: "detail"
		},
		toDeliverGoods = {
			label: "去发货",
			value: "deliverGoods"
		},
		checkLogistics = {
			label: "查看物流",
			value: "checkLogistics"
		},
		agree = {
			label: "同意",
			value: "agree"
		},
		refuse = {
			label: "拒绝",
			value: "refuse"
		};

	const newColumns = [
		...TABLE_COLUMNS,
		{
			title: "操作",
			width: 220,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "detail":
						navigate("/transaction/detail?order_id=" + record?.order_id);
						break;
					case "deliverGoods":
						navigate("/transaction/deliver?order_id=" + record?.order_id);
						break;
					case "checkLogistics":
						navigate("/transaction/flow?order_id=" + record?.order_id);
						break;
					case "agree":
						onAgree(record);
						break;
					case "refuse":
						onRefuse(record);
						break;
				}
			},
			options: (record: any) => {
				if (isWaitSales(record) || isPartialDelivery(record)) {
					return [detail, toDeliverGoods];
				} else if (isSales(record)) {
					return [detail, checkLogistics];
				} else if (isInRefunded(record)) {
					return isInRefundedWaitAudit(record) ? [detail, agree, refuse] : [detail];
				} else if (isSalesSuccess(record)) {
					return [detail, checkLogistics];
				}
				return [detail];
			}
		}
	];

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchOptions(tabValueInfo);
	}, [tabValueInfo]);

	return (
		<div
			className={cs({
				[styles.container]: true,
				[styles.dashboard]: isDashboard
			})}
		>
			{!isDashboard && (
				<>
					<Tabs
						items={items}
						activeKey={tabValueInfo.status}
						onChange={e => {
							setTabValueInfo({
								status: e
							});
							setParams({});
						}}
					/>
					<SearchBox key={tabValueInfo.status} columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch} />
				</>
			)}

			<SuperTable
				params={{
					...params,
					...tabValueInfo
				}}
				// bordered
				rowKey="order_id"
				columns={newColumns}
				request={handleRequest}
				scroll={{ x: "900" }}
				expandable={{
					expandedRowRender: record => {
						return (
							<Flex justify="space-between">
								<div className={styles.flexItem} title={record?.order_id}>
									订单编号：{record?.order_id}
								</div>
								<div className={styles.flexItem} title={record?.receiver_info?.name}>
									收件人：{record?.receiver_info?.name}
								</div>
								<div className={styles.flexItem} title={record?.receiver_info?.mobile}>
									电话：{record?.receiver_info?.mobile}
								</div>
								<div
									className={styles.flexItem}
									title={`${record?.receiver_info?.province}${record?.receiver_info?.city}${record?.receiver_info?.county}${record?.receiver_info?.address}`}
								>
									收货地址：
									{`${record?.receiver_info?.province}${record?.receiver_info?.city}${record?.receiver_info?.county}${record?.receiver_info?.address}`}
								</div>
								<div className={styles.flexItem} title={record?.created_at}>
									创建时间：{record?.created_at}
								</div>
							</Flex>
						);
					},
					expandedRowKeys,
					expandIcon: () => null,
					columnWidth: 0
				}}
			/>
		</div>
	);
};
